package compute;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Computer extends JFrame implements ActionListener{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JTextField displayer;
	private boolean isNewNum = true;

	public Computer() {
		setSize(300, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
		setLayout(new BorderLayout());
		inticomponent();
	}

	private void inticomponent() {
		JPanel top = new JPanel();
		add(top, BorderLayout.NORTH);
		displayer = new JTextField();
		top.setLayout(new BorderLayout());
		top.add(displayer);
		displayer.setHorizontalAlignment(JTextField.RIGHT);
		displayer.setEnabled(false);
		displayer.setFont(new Font("微软雅黑", Font.TRUETYPE_FONT, 24));
		displayer.setDisabledTextColor(Color.blue);
		displayer.setText("0");
		JButton clear = new JButton("清除");
		clear.addActionListener(this);
		top.add(clear, BorderLayout.EAST);
		String[] fu = { "7", "8", "9", "+", "4", "5", "6", "-", "1", "2", "3",
				"*", "0", ".", "=", "/" };
		JPanel center = new JPanel();
		center.setLayout(new GridLayout(4, 4));
		add(center, BorderLayout.CENTER);
		for (String s : fu) {
			JButton bt = new JButton(s);
			bt.addActionListener(this);
			center.add(bt);
		}
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			public void run() {
				new Computer();

			}
		});
	}
	public void actionPerformed(ActionEvent e) {
		String txt=e.getActionCommand();
		if(".0123456789".indexOf(txt)>=0){
			showNum(txt);
		}
		else if(txt.equals("清除")){
			displayer.setText("0");
		}
		else{
			isNewNum=true;
			String sourceTxt=displayer.getText();
			double sourceNum=Double.valueOf(sourceTxt);
			if(sourceTxt.indexOf("+,-,*,/")>=0){
				displayer.setText("0");
				
			}
		}
	}
	private void showNum(String txt) {
		if(isNewNum==true) displayer.setText("0");
		String sourceTxt=displayer.getText();
		double sourceNum=Double.valueOf(sourceTxt);
		if(sourceNum==0&&sourceTxt.indexOf(".")<0){
			if(txt.equals(".")) displayer.setText("0.");
			else displayer.setText(txt);
		}
		else{
			if(sourceTxt.indexOf(".")<0||!txt.equals("."))
			   displayer.setText(sourceTxt+txt);
		}
		isNewNum=false;
	}
}
